package com.alibaba.dubbo.governance.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.utils.ReferenceConfigCache;
import com.alibaba.dubbo.governance.service.RestService;
import com.alibaba.dubbo.governance.service.ZookeeperService;
import com.alibaba.dubbo.registry.common.domain.Invocation;
import com.alibaba.dubbo.rpc.service.GenericService;
import com.lvmama.pub.DistributedContext;

/**
 * @author xuchangyue
 */
public class RestServiceImpl implements RestService {
    private static final Logger logger = Logger.getLogger(RestServiceImpl.class);

    @Autowired
    private ZookeeperService zookeeperService;

    public Object call(Invocation invocation) {
        logger.info(invocation);

        DistributedContext.put("cache.passby", invocation.getIsPassedBy());
        GenericService genericService = getRef(invocation.getService(), invocation.getZkAddress());
        Object result = genericService.$invoke(invocation.getMethod(), invocation.getArgTypes(), invocation.getArguments());

        logger.info(result);
        return result;
    }

    private static <T> T getRef(String clazz, String zkAddress){
        if (StringUtils.isBlank(clazz) || StringUtils.isBlank(zkAddress)) {
            return null;
        }

        ReferenceConfig<T> referenceConfig = new ReferenceConfig<T>();
        referenceConfig.setInterface(clazz);
        referenceConfig.setGeneric(true);

        RegistryConfig registry = new RegistryConfig();
        registry.setAddress(zkAddress);
        registry.setProtocol("zookeeper");;
        referenceConfig.setRegistry(registry);

        ApplicationConfig application = new ApplicationConfig();
        application.setName("dubbo-admin");
        referenceConfig.setApplication(application);

        ReferenceConfigCache cache = ReferenceConfigCache.getCache();

        return cache.get(referenceConfig);
    }

    public void saveParamToZK(String path) {
        logger.info(path);
        zookeeperService.update(path);
    }

    public List<String> getArgNames(String path) {
        logger.info(path);
        return zookeeperService.getChildren(path);
    }

    public String getArgByName(String path) {
        logger.info(path);
        List<String> args = zookeeperService.getChildren(path);
        return (args != null && args.size() > 0) ? args.get(0) : "";
    }
}
